/**
 * Created by xmfang on 2014/12/11.
 */

var mongoose = require('mongoose');
var _ = require('underscore');
var moment = require('moment');
var async = require("async");
var response = require('./response');
var config = require('../conf/config');
var errorCode = config.errorCode;
var constant = config.constant;
var dateUtils = require('../util/scheduleDate');
var scheduleUtil = require('../util/scheduleUtil');
var messageSender = require('./messageSender');
var logRecorder = require('./logRecorder');

var Schedule = mongoose.model('Schedule');
var CustomRemind = mongoose.model('CustomRemind');
var CommentAndLog = mongoose.model('CommentAndLog');

//创建一个日程
exports.create = function (req, res) {
    var schedule = new Schedule(req.body);
    var memberId = req.session.user || schedule.sponsor;
    schedule.sponsor = memberId;

    var attendees = [{
        member : schedule.sponsor,
        attitude : constant.attitude.ACCEPT,
        reason : "",
        description : "",
        remind : schedule.remind
    }];
    var participantIds = [];
    if (req.body.participant) {     //加入参与人信息
        participantIds = _.uniq(_.without(req.body.participant, schedule.sponsor));
        _.each(participantIds, function (participantId) {
            attendees.push({
                member : participantId,
                reason : "",
                description : "",
                inviter : schedule.sponsor,
                remind : schedule.remind
            });
        });
    }
    schedule.attendees = attendees;

    //加上全天日程的开始结束时间
    if (schedule.isFullDay) {
        constant.scheduleType.MEETING == schedule.type ? schedule.timeScope.start.setHours(9,0,0,0) : schedule.timeScope.end.setHours(9,0,0,0);
    }

    schedule.save(function(error, theSchedule) {
        if (error) {
            console.error('创建日程：' + error);
            response.error(res, errorCode.databaseError);
        } else {
            //记录保存提醒信息
            var startTime = theSchedule.type == constant.scheduleType.MEETING ? theSchedule.timeScope.start : theSchedule.timeScope.end;
            var remind = theSchedule.isFullDay ? theSchedule.remind * 60 * 24 : theSchedule.remind;
            saveRemind(theSchedule._id, _.pluck(theSchedule.attendees, 'member'), startTime, remind, theSchedule.repeat);

            response.data(res, theSchedule);

            //给参与人发邀请消息
            if (participantIds && participantIds.length > 0) {
                messageSender.sendInvitationMessage(req.body.memberName, participantIds, theSchedule);
            }
        }
    });
};

//保存提醒信息
var saveRemind = function (scheduleId, members, startTime, leadMinute, repeatPeriod) {
    if (leadMinute < 0) return;
    var alarmTime = new Date(startTime.getTime() - leadMinute * 60 * 1000);
    _.each(members, function (member) {
        var customRemind = new CustomRemind({
            scheduleId : scheduleId,
            memberId : member,
            leadMinute : leadMinute,
            alarm : alarmTime,
            repeat : repeatPeriod
        });
        customRemind.save(function (error, data) {
            if (error) {
                console.error('创建提醒记录时出错：' + error);
                response.error(res, errorCode.databaseError);
            }
        });
    });
};

//根据ID获取一个日程
exports.get = function (req, res) {
    Schedule.findById(req.params.id, function (error, schedule) {
        if (error) {
            console.error('根据ID获取日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            CommentAndLog.count({
                scheduleId : req.params.id
                //type : constant.CommentOrLog.COMMENT
            }, function (error, count) {
                if (error) {
                    console.error('根据ID获取日程时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                } else if (!schedule) {
                    response.data(res, errorCode.scheduleIsNotExist);
                } else {
                    schedule._doc.commentCount = count;
                    var memberId = req.session.user;  //TODO 当前用户，目前没有用户ID ,暂时固定使用zhangsan
                    _.each(schedule.attendees, function (attendee) {
                        if (attendee.member == memberId) {
                            schedule._doc.isAccepted = (attendee.attitude === constant.attitude.ACCEPT);
                            schedule._doc.isDone = attendee.isCompleted;
                            return false;
                        }
                    });
                    response.data(res, schedule);
                }
            });
        }
    });
};

//多条件筛选查询日程
exports.query = function (req, res) {
    var conditions = {repeat : constant.period.NONE};
    assemConditions(req.body, conditions);

    Schedule.find(conditions).sort({'timeScope.start' : 'asc'}).exec(function (error, noRepeatSchedules) {
        if (error) {
            console.error('多条件筛选查询非重复性日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            conditions.repeat = { $not : {$eq : constant.period.NONE}};
            conditions['deadline'] = {$gte : moment(req.body.date)};
            conditions['timeScope.start'] = {$lte : moment(req.body.date).add('days', 1)};
            delete conditions['timeScope.end'];
            Schedule.find(conditions).sort({'timeScope.start' : 'asc'}).exec(function (error, repeatSchedules) {
                if (error) {
                    console.error('多条件筛选查询重复性日程时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                } else {
                    response.data(res, {
                        'noRepeatSchedules' : noRepeatSchedules,
                        'repeatSchedules' : repeatSchedules
                    });
                }
            });

        }
    });
};

//组装条件
var assemConditions = function (reqBody, conditions) {
    if (reqBody.subject) {
        conditions['subject'] = new RegExp("^.*" + reqBody.subject + ".*$", 'i');
    }
    if (reqBody.date) {
        conditions['timeScope.start'] = {$lt : moment(reqBody.date).add('days',1)};
        conditions['timeScope.end'] = {$gte : moment(reqBody.date)};
    }
    if (reqBody.type) {
        conditions['type'] = reqBody.type;
    }

    if (reqBody.isCompleted) {
        conditions['attendees'] = {$elemMatch : {isCompleted : true}};
    } else if (reqBody.isCompleted == false) {
        conditions['attendees'] = {$elemMatch : {isCompleted : false}};
    }

    if (reqBody.isSponsor) {
        conditions['sponsor'] = reqBody.memberId;
    } else if (reqBody.isSponsor == false) {
        conditions['sponsor'] = {$ne : reqBody.memberId};
        if (conditions.attendees) conditions.attendees.$elemMatch = {member : reqBody.memberId};
        else conditions.attendees = {$elemMatch : {member : reqBody.memberId}};
        conditions.attendees.$elemMatch.attitude = constant.attitude.ACCEPT;
    } else {
        if (conditions.attendees) conditions.attendees.$elemMatch = {member : reqBody.memberId};
        else conditions.attendees = {$elemMatch : {member : reqBody.memberId}};
        conditions.attendees.$elemMatch.attitude = constant.attitude.ACCEPT;
    }
};

//查询某个时间段内的日程
exports.queryByDateScope = function (req, res) {
    queryByDateScopeFun(req.params.memberId, req.params.startDate, req.params.endDate, function (error, result) {
        if (error) {
            console.error('查询某个时间段内的日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            response.data(res, result);
        }
    });
};

var queryByDateScopeFun = function (memberId, startDate, endDate, callback) {
    Schedule.find({
        'timeScope.start' : {'$gte' : startDate, '$lt' : moment(endDate).add('days',1)},
        'attendees' : {'$elemMatch' : {'member' : memberId, 'attitude' : constant.attitude.ACCEPT}}
        //'$or' : [{'sponsor' : memberId}, {'attendees' : {'$elemMatch' : {'member' : memberId}}}]
    }, callback);
};

//根据用户ID查询某个时间段内的非重复性日程、重复性日程和未确认的日程邀请数目
exports.queryByDateScopeAndUncCount = function (req, res) {
    var memberId = req.session.user || req.params.memberId;

    queryNoRepeatByDateScopeFun(memberId, req.params.startDate, req.params.endDate, function (error, noRepeatSchedules) {
        if (error) {
            console.error('查询某个时间段内的非重复性日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            queryRepeatScheduleFunc(memberId, function (error, repeatSchedules) {
                if (error) {
                    console.error('查询重复日程时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                } else {
                    queryUnconfirmed(memberId, function (err, result) {
                        if (err) {
                            console.error('查询待确认日程时出错： ' + error);
                            response.error(res, errorCode.databaseError);
                        } else {
                            response.data(res, {
                                'noRepeatSchedules' : noRepeatSchedules,
                                'repeatSchedules' : sortRepeatSchedule(repeatSchedules),
                                'unconfirmedCount' : result.length
                            });
                        }
                    });
                }
            }, req.params.startDate, req.params.endDate);
        }
    });
};

var queryNoRepeatByDateScopeFun = function (memberId, startDate, endDate, callback) {
    Schedule.find({
        'timeScope.start' : {'$gte' : startDate, '$lt' : moment(endDate).add('days',1)},
        'attendees' : {'$elemMatch' : {'member' : memberId, 'attitude' : constant.attitude.ACCEPT}},
        'repeat' : constant.period.NONE
        //'$or' : [{'sponsor' : memberId}, {'attendees' : {'$elemMatch' : {'member' : memberId}}}]
    }, callback);
};

var sortRepeatSchedule = function (schedules) {
    if (!schedules) {
        return [];
    }
    var result = [];
    result = result.concat(categoryRepeatSchedule(schedules, constant.period.DAY));
    result = result.concat(categoryRepeatSchedule(schedules, constant.period.WEEK));
    result = result.concat(categoryRepeatSchedule(schedules, constant.period.MONTH));
    result = result.concat(categoryRepeatSchedule(schedules, constant.period.YEAR));
    return result;
};

var categoryRepeatSchedule = function (schedules, periodCategory) {
    var condition = {repeat : periodCategory};
    return _.where(schedules, condition);
};

//根据人员ID查询其未确认的日程
var queryUnconfirmed = function (memberId, callback) {
    Schedule.find({
        'attendees' : {'$elemMatch' : {'member' : memberId, 'attitude' : constant.attitude.NEUTRAL}}
    }, callback);
};

var queryRepeatScheduleFunc = function (memberId, callback, queryStartTime, queryEndTime) {
    var conditions = {
        repeat : {$not : {$eq : constant.period.NONE}},
        attendees : {$elemMatch : {member : memberId, attitude : constant.attitude.ACCEPT}}
        //$or : [{sponsor : memberId}, {attendees : {$elemMatch : {member : memberId}}}]
    };
    if (queryStartTime) {
        conditions.deadline = {$gte : moment(queryStartTime)};
    }
    if (queryEndTime) {
        conditions['timeScope.start'] = {$lt : moment(queryEndTime).add('days', 1)};
    }
    Schedule.find(conditions, callback);
};

//根据成员ID查询重复的日程
exports.queryRepeat = function (req, res) {
    queryRepeatScheduleFunc(req.params.memberId, function (error, results) {
        if (error) {
            console.error('查询重复日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            response.data(res, results);
        }
    });
};

//根据ID修改日程
exports.update = function (req, res) {
    var schedule = req.body.schedule;
    //加上全天日程的开始结束时间
    if (schedule.isFullDay) {
        if (constant.scheduleType.MEETING) {
            var start = new Date(schedule.timeScope.start);
            start.setHours(9,0,0,0);
            schedule.timeScope.start = start;
        } else {
            var end = new Date(schedule.timeScope.start);
            end.setHours(9,0,0,0);
            schedule.timeScope.end = end;
        }
    }
    var remind = schedule.remind;
    delete schedule.remind;
    Schedule.findByIdAndUpdate(schedule._id, schedule, {new : false}, function (error, oldSchedule) {
        if (error) {
            console.error('修改日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else if (!oldSchedule) {
            response.data(res, errorCode.scheduleIsNotExist)
        } else {
            //如果提前提醒时间，重复周期和日程开始时间中的一个发生修改，则要修改相应的提醒信息记录
            var remindTime, oldRemindTime;
            if (oldSchedule.type == constant.scheduleType.MEETING) {
                remindTime = schedule.timeScope.start;
                oldRemindTime = oldSchedule.timeScope.start;
            } else {
                remindTime = schedule.timeScope.end;
                oldRemindTime = oldSchedule.timeScope.end;
            }

            if (schedule.remind != oldSchedule.remind
                || schedule.repeat != oldSchedule.repeat
                || remindTime != oldRemindTime) {
                var remindMimute = schedule.isFullDay ? remind * 60 * 24 : remind;
                updateRemind(schedule._id, oldSchedule.sponsor, remindTime, remindMimute, remind, schedule.repeat, function (error, data) {
                    if (error) {
                        console.error('修改提醒信息时出错： ' + error);
                        response.error(res, errorCode.databaseError);
                    }
                });
            }

            //给日程添加参与人
            var joinParticipants = wipeRepeatParticipant(req.body.newParticipant, oldSchedule.attendees, oldSchedule.sponsor, oldSchedule.remind);
            participantJoin(schedule._id, joinParticipants, function (error, data) {
                if (error) {
                    console.error('给日程添加参与人时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                } else {   //给日程删除参与人
                    var quitParticipantIds = req.body.removeParticipant || [];
                    participantQuit(schedule._id, quitParticipantIds, function (error, data) {
                        if (error) {
                            console.error('删除日程参与人时出错： ' + error);
                            response.error(res, errorCode.databaseError);
                        } else {
                            response.success(res);
                        }
                    });
                }
            });

            //根据修改的信息发消息
            var memberIds = [];
            _.each(oldSchedule.attendees, function (attendee) {
                if (attendee.member != oldSchedule.sponsor && !_.contains(req.body.removeParticipant, attendee.member)) {
                    memberIds.push(attendee.member);
                }
            });

            if (memberIds.length > 0) {
                schedule.sponsor = oldSchedule.sponsor;
                messageSender.sendScheduleChangeMessage(schedule, oldSchedule, memberIds);
            }

            //发消息给新的被邀请人
            if (joinParticipants) {
                messageSender.sendInvitationMessage(schedule.memberName, _.pluck(joinParticipants, 'member'), schedule);
            }

            //发消息给被删除的被邀请人
            if (req.body.removeParticipant && req.body.removeParticipant.length > 0) {
                messageSender.sendCancelInvitationMessage(req.body.removeParticipant, oldSchedule);
            }
        }
    });
};

var wipeRepeatParticipant = function (joinParticipantIds, oldparticipants, inviter, remind) {
    if (!joinParticipantIds) return null;
    if (joinParticipantIds.length == 0) return null;
    var result = [];
    var oldParticipantIds = _.pluck(oldparticipants, 'member');
    _.each(joinParticipantIds, function(participantId) {
        if (!_.contains(oldParticipantIds, participantId)) {
            result.push({
                member : participantId,
                reason : "",
                description : "",
                inviter : inviter,
                remind : remind
            });
        }
    });
    return result;
};

var participantJoin = function (scheduleId, joinParticipant, callback) {
    if (!joinParticipant) {
        callback();
        return;
    }
    Schedule.findByIdAndUpdate(scheduleId, {
        "$push" : {"attendees" : {$each : joinParticipant}}
    }, callback);
};

var participantQuit = function (scheduleId, quitParticipantIds, callback) {
    if (!quitParticipantIds) {
        callback();
        return;
    }
    Schedule.update({_id : scheduleId}, {
        "$pull" : {"attendees" : {"member" : {$in : quitParticipantIds}}}
    }, callback);
};

var updateRemind = function (scheduleId, memberId, startTime, leadMinute, remind, repeatPeriod, callback) {
    if (leadMinute < 0) {
        removeCustomRemind(scheduleId, memberId);
        callback();
        return;
    }
    var alarmTime = repeatPeriod && repeatPeriod != constant.period.NONE ?
        dateUtils.recalculateNextRemindTime(startTime, leadMinute, repeatPeriod) : new Date(moment(startTime).toDate().getTime() - leadMinute * 60 * 1000);
    CustomRemind.findOneAndUpdate({
        'scheduleId' : scheduleId,
        'memberId' : memberId
    }, {
        leadMinute : leadMinute,
        alarm : alarmTime,
        repeat : repeatPeriod
    },{new : false}, function (error, customRemind) {
        if (error) {
            console.error('更改提醒时间时出错： ' + error);
            callback();
        } else {
            if (!customRemind) {
                saveRemind(scheduleId, [memberId], moment(startTime).toDate(), leadMinute, repeatPeriod);
            }

            Schedule.findOneAndUpdate({
                _id: scheduleId,
                'attendees.member': memberId
            }, {
                'attendees.$.remind': remind
            }, callback);
        }
    });
};

var removeCustomRemind = function (scheduleId, memberId) {
    CustomRemind.remove({
        'scheduleId' : scheduleId,
        'memberId' : memberId
    }, function (error, data) {
        if (error) {
            console.error('删除提醒记录时出错： ' + error);
            response.error(res, errorCode.databaseError);
        }
    });
};

//普通参与人修改提醒时间和邀请新的参与人
exports.memberUpdate = function (req, res) {
    Schedule.findById(req.body.scheduleId, function (error, schedule) {
        if (error) {
            console.error('根据ID查找日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else if (!schedule) {
            response.data(res, errorCode.scheduleIsNotExist);
        } else {
            var remindMimute = schedule.isFullDay ? req.body.remind * 60 * 24 : req.body.remind;
            updateRemind(req.body.scheduleId, req.body.memberId, schedule.timeScope.start, remindMimute, req.body.remind, schedule.repeat, function (error, data) {
                if (error) {
                    console.error('参与人修改提醒时间时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                } else if (req.body.newParticipant) {
                    var joinParticipants = wipeRepeatParticipant(req.body.newParticipant, schedule.attendees, req.body.memberId, schedule.remind);
                    participantJoin(req.body.scheduleId, joinParticipants, function (error, data) {
                        if (error) {
                            console.error('参与人添加新参与人时出错： ' + error);
                            response.error(res, errorCode.databaseError);
                        } else {
                            response.success(res);
                            //发消息给新的被邀请人
                            if (joinParticipants) {
                                messageSender.sendInvitationMessage(req.body.memberName, _.pluck(joinParticipants, 'member'), schedule);
                            }
                        }
                    });
                } else {
                    response.success(res);
                }
            });
        }
    });
};

//根据ID删除日程
exports.remove = function (req, res) {
    var scheduleId = req.body.scheduleId;
    Schedule.findByIdAndRemove(scheduleId, function (error, schedule) {
        if (error) {
            console.error('删除日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            CustomRemind.remove({'scheduleId' : scheduleId}, function (error, data) {
                if (error) {
                    console.error('删除日程相关的提醒时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                }
            });
            CommentAndLog.remove({'scheduleId' : scheduleId}, function (error, data) {
                if (error) {
                    console.error('删除日程相关的评论和日志时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                }
            });
            response.success(res);

            var memberIds = _.pluck(getNonRefuseAttendees(schedule.attendees, schedule.sponsor), 'member');
            if (memberIds.length > 0) {
                messageSender.sendCancelScheduleMessage(memberIds, schedule);
            }
        }
    });
};

//根据用户ID查询待其确认的日程
exports.queryUnconfirmedInvite = function (req, res) {
    queryUnconfirmed(req.params.memberId, function (error, results) {
        if (error) {
            console.error('查询待确认日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        }
        response.data(res, results);
    });
};

//参与人表态是否接受任务
exports.memberStand = function (req, res) {
    Schedule.update({
        _id : req.body.scheduleId,
        'attendees.member' : req.body.memberId
    }, {
        'attendees.$.attitude' : req.body.attitude,
        'attendees.$.reason' : req.body.reason
    }, function (error, data) {
        if (error) {
            console.error('修改参与人表态时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            response.success(res);
            Schedule.findById(req.body.scheduleId, function (error, schedule) {
                if (error) {
                    console.error('根据ID查询日程时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                } else {
                    if (req.body.attitude == constant.attitude.ACCEPT) {
                        messageSender.sendAcceptInvitationMessage(req.body.memberId, req.body.memberName, schedule);
                        logRecorder.recordAccept(req.body.memberId, req.body.scheduleId);
                    } else {
                        messageSender.sendRefuseInvitationMessage(req.body.memberId, req.body.memberName, req.body.reason, schedule);
                        logRecorder.recordRefuse(req.body.memberId, req.body.scheduleId, req.body.reason);
                    }
                }
            });
        }
    });
};

//重新发起邀请
exports.memberReinvite = function (req, res) {
    Schedule.findOneAndUpdate({
        _id : req.body.scheduleId,
        'attendees.member' : req.body.memberId
    }, {
        'attendees.$.attitude' : constant.attitude.NEUTRAL
    }, function (error, schedule) {
        if (error) {
            console.error('根据ID查询日程时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            response.success(res);
            messageSender.sendInvitationMessage(req.body.inviterName, [req.body.memberId], schedule)
        }
    });
};

//参与人完成任务
exports.completeTask = function (req, res) {
    Schedule.update({
        _id : req.body.scheduleId,
        'attendees.member' : req.body.memberId
    }, {
        'attendees.$.isCompleted' : true,
        'attendees.$.description' : req.body.description
    }, function (error, data) {
        if (error) {
            console.error('参与人完成任务时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            response.success(res);
            logRecorder.recordCompleteTask(req.body.memberId, req.body.scheduleId, req.body.description);
            Schedule.findById(req.body.scheduleId, function (error, schedule) {
                if (error) {
                    console.error('为完成任务发消息而根据ID获取日程时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                } else {
                    var memberIds = getAcceptAttendees(schedule.attendees, req.body.memberId);
                    if (memberIds.length > 0) {
                        messageSender.sendCompeletedTaskMessage(_.pluck(memberIds, 'member'), schedule, req.body.memberName);
                    }
                }
            });
        }
    });
};

//参与人重启一个任务
exports.restartTask = function (req, res) {
    Schedule.update({
        _id : req.body.scheduleId,
        'attendees.member' : req.body.memberId
    }, {
        'attendees.$.isCompleted' : false
    }, function (error, data) {
        if (error) {
            console.error('参与人重启任务时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            response.success(res);
            logRecorder.recordRestartTask(req.body.memberId, req.body.scheduleId);
            Schedule.findById(req.body.scheduleId, function (error, schedule) {
                if (error) {
                    console.error('为重启任务发消息而根据ID获取日程时出错： ' + error);
                    response.error(res, errorCode.databaseError);
                } else {
                    var memberIds = getAcceptAttendees(schedule.attendees, req.body.memberId);
                    if (memberIds.length > 0) {
                        messageSender.sendRestartTaskMessage(_.pluck(memberIds, 'member'), schedule, req.body.memberName);
                    }
                }
            });
        }
    });
};

var getAcceptAttendees = function (attendees, memberId) {
    return _.filter(attendees, function (attendee) {
        return attendee.attitude === config.constant.attitude.ACCEPT && attendee.member != memberId;
    });
};

var getNonRefuseAttendees = function (attendees, memberId) {
    return _.filter(attendees, function (attendee) {
        return attendee.attitude != config.constant.attitude.REFUSE && attendee.member != memberId;
    });
};

//提交创建好的讨论组ID
exports.commitGroupId = function (req, res) {
    Schedule.update({
        _id : req.body.scheduleId
    }, {
        groupId : req.body.groupId
    }, function (error, data) {
        if (error) {
            console.error('提交讨论组ID时出错： ' + error);
            response.error(res, errorCode.databaseError);
        } else {
            response.success(res);
        }
    });
};

exports.lisQuery = function(req, res){
    var size = req.body.size;
    var startTime = req.body.startTime;
    var type = req.body.type;
    var isFirstPage = req.body.isFirstPage;
    var memberId = req.body.memberId || req.session.user;
    var condition = null;
    var sortCondition = {
        'NEXT' : {'timeScope.start' : 'asc'},
        'BACK' : {'timeScope.start' : 'desc'}
    };

    if (isFirstPage) {
        var command = {
            'NEXT' : {'deadline' : {'$gte' : moment(startTime).toDate()}},
            'BACK': {'timeScope.start' : {'$lte' : moment(startTime).toDate()}}
        };
        condition = command[type];
    } else {
        var command = {
            'NEXT' : {'deadline' : {'$gte' : moment(startTime).toDate()}},
            'BACK': {'timeScope.start' : {'$lt' : moment(startTime).toDate()}}
        };
        condition = command[type];
    }

    _.extend(condition, {'attendees' : {'$elemMatch' : {'member' : memberId, 'attitude' : constant.attitude.ACCEPT}}});

    async.parallel([function(callback){
        // 查询重复
        Schedule.find(_.extend({'repeat' : {$ne : constant.period.NONE}}, condition)).exec(function(error, schedules){
            callback(error, schedules);
        });
    }, function(callback){
        var conditionNotRepeat = _.extend({'repeat' : constant.period.NONE}, condition);

        if (isFirstPage && type == 'NEXT') {
            _.extend(conditionNotRepeat, {'timeScope.end' : {'$gte' : moment(startTime).toDate()}})
        } else if (type == 'NEXT') {
            _.extend(conditionNotRepeat, {'timeScope.start' : {'$gt' : moment(startTime).toDate()}})
        }
        // 查询不重复
        Schedule.find(conditionNotRepeat).limit(size + 5).sort(sortCondition[type]).exec(function(error, schedules){
            callback(error, schedules);
        });
    }], function(error, schedules){
        if (error) {
            console.error('列表查询出错:%s ', JSON.stringify(error));
            response.error(res, errorCode.databaseError);
        } else {
            var repeatSchedule = scheduleUtil.computeBySize(_.map(schedules[0], function(item){
                return item.toObject();
            }), startTime, type, size, isFirstPage);
            var notRepeatSchedule = _.map(schedules[1], function(item){
                return item.toObject();
            });

            // 两个合并为一
            _.each(notRepeatSchedule, function(schedule){
                schedule.pointTime = schedule.timeScope.start;
                repeatSchedule.push(schedule);
            });

            // 按时间排序
            var theSchedules = _.sortBy(repeatSchedule, function(schedule){
                return schedule.pointTime;
            });

            if (type == 'BACK') {
                theSchedules.reverse();
            }


            var result = _.first(theSchedules, size);
            while (true) {
                if (theSchedules[size]) {
                    if (moment(theSchedules[size].pointTime).diff(theSchedules[size - 1].pointTime) == 0) {
                        result.push(theSchedules[size]);
                        size ++;
                        continue;
                    }
                }
                break;
            }

            response.data(res, result);
        }
    });
};
